package com.asset.dispoal.file.casedispose.strategy;

import com.alibaba.excel.EasyExcel;
import com.asset.dispoal.business.bsCase.domain.db.entity.BsCase;
import com.asset.dispoal.business.bsCase.domain.db.mapper.BsCaseMapper;
import com.asset.dispoal.business.casedispose.domain.db.mapper.CasedisposeMapper;
import com.asset.dispoal.business.casedispose.domain.dto.CaseDisposeState;
import com.asset.dispoal.commom.menus.AgreementCaseSateMenu;
import com.asset.dispoal.file.casedispose.dto.FileCaseBatchEditRequest;
import com.asset.dispoal.file.casedispose.strategy.dto.ExecutionExcelUploadDTO;
import com.asset.dispoal.file.casedispose.strategy.dto.JudgmentExcelUploadDTO;
import com.asset.dispoal.file.casedispose.strategy.dto.RegisterExcelUploadDTO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.ObjectUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: yf
 * @date: 2022-10-14 14:59:40
 */
@Slf4j
@Component
public class FileBatchUpdateStrategyManager {
    @Autowired
    private CasedisposeMapper casedisposeMapper;
    @Autowired
    private BsCaseMapper bsCaseMapper;


    public static Map<String, Function<FileCaseBatchEditRequest, Result>> strategyMap = new ConcurrentHashMap<>();

    @PostConstruct
    void init() {
        //key 为方式，在修改中理解为文件类型
        strategyMap.put("1", this::updateRegisterCase);
        strategyMap.put("2", this::updateMeditionUpCase);
        strategyMap.put("3", this::updateJudgmentCase);
        strategyMap.put("4", this::updatEexecutionCase);
        strategyMap.put("10", this::updatStepJudgmentCase);
    }

    public Result getResult(FileCaseBatchEditRequest request) {
        Function<FileCaseBatchEditRequest, Result> function = strategyMap.get(request.getMode());
        if (function != null) {
            return function.apply(request);
        }
        log.error("未找到文件类型！");
        return Result.faild("修改失败，未找到文件类型！");
    }

    /**
     * 修改立案类型文件的状态
     *
     * @param request
     * @return
     */
    @SneakyThrows
    private Result updateRegisterCase(FileCaseBatchEditRequest request) {
        List<CaseDisposeState> caseStateList = casedisposeMapper.queryCaseStateByAppointId(request.getAppointId());
        if (CollectionUtil.isEmpty(caseStateList)) {
            return Result.faild("批次包的案件不存在");
        }

        List<RegisterExcelUploadDTO> idCardList = EasyExcel.read(request.getFile().getInputStream()).head(RegisterExcelUploadDTO.class).sheet().doReadSync();
        if (CollectionUtil.isEmpty(idCardList)) {
            return Result.faild("身份证号不存在");
        }
        Map<String, RegisterExcelUploadDTO> registerExcelUploadDTOMap = idCardList.stream().collect(Collectors.toMap(RegisterExcelUploadDTO::getIdCard, dto -> dto));
        boolean checked = Boolean.TRUE;
        GlobalHeaderThreadLocal.get().getUserId();
        StringBuilder builderStr = new StringBuilder();
        for (CaseDisposeState caseDisposeState : caseStateList) {
            RegisterExcelUploadDTO dto = registerExcelUploadDTOMap.get(caseDisposeState.getIdCard());
            if (ObjectUtil.isNotEmpty(dto)) {
                checked = false;
                //修改案件表状态
                BsCase bsCase = new BsCase();
                bsCase.setId(caseDisposeState.getId());
//                bsCase.setOperateUser(userId);
//                bsCase.setOperateTime(DateTimeUtil.currentDate());
                bsCase.setRegisterCaseTime(dto.getRegisterCaseTime());
                bsCase.setLitigationNumber(dto.getLitigationNumber());
                bsCase.setLitigationAmount(dto.getLitigationAmount());
                bsCase.setPreservationAmount(dto.getPreservationAmount());
                int updateRes = bsCaseMapper.update(bsCase);
                if (updateRes <= 0) {
                    builderStr.append("身份证号为:").append(caseDisposeState.getIdCard()).append(" 的记录修改失败").append("<br/><br/>");
                }
            }
        }
        if (checked) {
            return Result.faild("找不到导入条件的身份证号");
        }
        return Result.ok(builderStr);
    }

    /**
     * 诉前调解文件类型
     *
     * @param request
     * @return
     */
    private Result updateMeditionUpCase(FileCaseBatchEditRequest request) {
        return Result.ok();
    }

    /**
     * 修改判决类型的文件
     *
     * @param request
     * @return
     */
    @SneakyThrows
    private Result updateJudgmentCase(FileCaseBatchEditRequest request) {
        List<CaseDisposeState> caseStateList = casedisposeMapper.queryCaseStateByAppointId(request.getAppointId());
        if (CollectionUtil.isEmpty(caseStateList)) {
            return Result.faild("批次包的案件不存在");
        }
        caseStateList = caseStateList.stream().filter(caseState -> AgreementCaseSateMenu.REGISTER_CASE.getLabel().equals(caseState.getState())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(caseStateList)) {
            return Result.faild("批次包下的案件没有待立案的案件");
        }

        List<JudgmentExcelUploadDTO> idCardList = EasyExcel.read(request.getFile().getInputStream()).head(JudgmentExcelUploadDTO.class).sheet().doReadSync();
        if (CollectionUtil.isEmpty(idCardList)) {
            return Result.faild("身份证号不存在");
        }
        Map<String, JudgmentExcelUploadDTO> judgmentExcelUploadDTOIdCardMap = idCardList.stream().collect(Collectors.toMap(JudgmentExcelUploadDTO::getIdCard, dto -> dto));
        Map<String, JudgmentExcelUploadDTO> judgmentExcelUploadDTOLitigationNumberMap = idCardList.stream().collect(Collectors.toMap(JudgmentExcelUploadDTO::getLitigationNumber, dto -> dto));
        boolean checked = Boolean.TRUE;
        GlobalHeaderThreadLocal.get().getUserId();
        StringBuilder builderStr = new StringBuilder();
        for (CaseDisposeState caseDisposeState : caseStateList) {
            JudgmentExcelUploadDTO dto = judgmentExcelUploadDTOIdCardMap.get(caseDisposeState.getIdCard());
            if (ObjectUtil.isEmpty(dto)) {
                dto = judgmentExcelUploadDTOLitigationNumberMap.get(caseDisposeState.getLitigationNumber());
            }
            if (ObjectUtil.isNotEmpty(dto)) {
                checked = false;
                BsCase bsCase = new BsCase();
                bsCase.setId(caseDisposeState.getId());
//                bsCase.setOperateUser(userId);
//                bsCase.setOperateTime(DateTimeUtil.currentDate());
                bsCase.setJudgmentTime(dto.getJudgmentTime());
                bsCase.setPrincipal(dto.getPrincipal());
                bsCase.setInterest(dto.getInterest());
                bsCase.setPenaltyInterest(dto.getPenaltyInterest());
                bsCase.setCaseAcceptAmount(dto.getCaseAcceptAmount());
                bsCase.setJudgmentPreservationAmount(dto.getJudgmentPreservationAmount());
                bsCase.setBaseNumber1(dto.getBaseNumber1());
                bsCase.setBaseNumber2(dto.getBaseNumber2());
                bsCase.setBaseNumber3(dto.getBaseNumber3());
                bsCase.setBaseNumber4(dto.getBaseNumber4());
                bsCase.setBaseNumber5(dto.getBaseNumber5());
                bsCase.setJudgmentType1(dto.getJudgmentType1());
                bsCase.setJudgmentType2(dto.getJudgmentType2());
                bsCase.setJudgmentType3(dto.getJudgmentType3());
                bsCase.setJudgmentType4(dto.getJudgmentType4());
                bsCase.setJudgmentType5(dto.getJudgmentType5());
                bsCase.setJudgmentRate1(dto.getJudgmentRate1());
                bsCase.setJudgmentRate2(dto.getJudgmentRate2());
                bsCase.setJudgmentRate3(dto.getJudgmentRate3());
                bsCase.setJudgmentRate4(dto.getJudgmentRate4());
                bsCase.setJudgmentRate5(dto.getJudgmentRate5());
                bsCase.setJudgmentCalculationTime1(dto.getJudgmentCalculationTime1());
                bsCase.setJudgmentCalculationTime2(dto.getJudgmentCalculationTime2());
                bsCase.setJudgmentCalculationTime3(dto.getJudgmentCalculationTime3());
                bsCase.setJudgmentCalculationTime4(dto.getJudgmentCalculationTime4());
                bsCase.setJudgmentCalculationTime5(dto.getJudgmentCalculationTime5());
                bsCase.setJudgmentDay1(dto.getJudgmentDay1());
                bsCase.setJudgmentDay2(dto.getJudgmentDay2());
                bsCase.setJudgmentDay3(dto.getJudgmentDay3());
                bsCase.setJudgmentDay4(dto.getJudgmentDay4());
                bsCase.setJudgmentDay5(dto.getJudgmentDay5());
                bsCase.setBrief(dto.getBrief());
                bsCase.setJudge(dto.getJudge());
                int updateRes = bsCaseMapper.update(bsCase);
                if (updateRes <= 0) {
                    builderStr.append("身份证号为:").append(caseDisposeState.getIdCard()).append("的记录修改失败").append("<br/><br/>");
                }
            }
        }
        if (checked) {
            return Result.faild("找不到导入条件的身份证号");
        }
        return Result.ok(builderStr);
    }

    /**
     * 执行  主要作用更改执行时间
     *
     * @param request
     * @return
     */
    @SneakyThrows
    private Result updatEexecutionCase(FileCaseBatchEditRequest request) {
        List<CaseDisposeState> caseStateList = casedisposeMapper.queryCaseStateByAppointId(request.getAppointId());
        if (CollectionUtil.isEmpty(caseStateList)) {
            return Result.faild("批次包的案件不存在");
        }
        caseStateList = caseStateList.stream().filter(caseState -> AgreementCaseSateMenu.JUDGMENT.getLabel().equals(caseState.getState())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(caseStateList)) {
            return Result.faild("批次包下的案件没有待立案的案件");
        }

        List<ExecutionExcelUploadDTO> idCardList = EasyExcel.read(request.getFile().getInputStream()).head(ExecutionExcelUploadDTO.class).sheet().doReadSync();
        if (CollectionUtil.isEmpty(idCardList)) {
            return Result.faild("身份证号不存在");
        }
        Map<String, ExecutionExcelUploadDTO> executionExcelUploadDTOIdCardMap = idCardList.stream().collect(Collectors.toMap(ExecutionExcelUploadDTO::getIdCard, dto -> dto));
        Map<String, ExecutionExcelUploadDTO> executionExcelUploadDTOLitigationNumberMap = idCardList.stream().collect(Collectors.toMap(ExecutionExcelUploadDTO::getLitigationNumber, dto -> dto));
        boolean checked = Boolean.TRUE;
        String userId = GlobalHeaderThreadLocal.get().getUserId();
        StringBuilder builderStr = new StringBuilder();

        for (CaseDisposeState caseDisposeState : caseStateList) {
            ExecutionExcelUploadDTO dto = executionExcelUploadDTOIdCardMap.get(caseDisposeState.getIdCard());
            if (ObjectUtil.isEmpty(dto)) {
                dto = executionExcelUploadDTOLitigationNumberMap.get(caseDisposeState.getLitigationNumber());
            }
            if (ObjectUtil.isNotEmpty(dto)) {
                checked = false;
                BsCase bsCase = new BsCase();
                bsCase.setId(caseDisposeState.getId());
                bsCase.setOperateUser(userId);
                bsCase.setOperateTime(DateTimeUtil.currentDate());
                bsCase.setExecutionTime(dto.getExecutionTime());
                bsCase.setExecutionNumber(dto.getExecutionNumber());
                int updateRes = bsCaseMapper.update(bsCase);
                if (updateRes <= 0) {
                    builderStr.append("身份证号为:").append(caseDisposeState.getIdCard()).append("的记录修改失败").append("<br/><br/>");
                }
            }
        }

        if (checked) {
            return Result.faild("找不到导入条件的身份证号");
        }

        return Result.ok(builderStr);
    }

    /**
     * 一步判决
     *
     * @param request
     * @return
     */
    @SneakyThrows
    private Result updatStepJudgmentCase(FileCaseBatchEditRequest request) {
        return Result.ok();
    }
}
